package com.ugoodtech.mdcc.client.service.impl;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.controller.ResponseObject.StationRegularReport;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.AliSmsProvider;
import com.ugoodtech.mdcc.client.service.StationServiceReportService;
import com.ugoodtech.mdcc.client.service.UserLogService;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.LogConstants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.domain.TechColorAuditingReports.TechColorAuditingReports;
import com.ugoodtech.mdcc.core.dto.AdminUserVo;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.service.UserAdminService;
import com.ugoodtech.mdcc.core.service.WechatService;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class StationServiceReportServiceImpl implements StationServiceReportService {

    @Autowired
    private StationRegularServiceReportRepository stationRegularServiceReportRepository;

    @Autowired
    private StationColorReportRepository stationColorReportRepository;

    @Autowired
    private StationRegularServiceReportUnFinshedRepository stationRegularServiceReportUnFinshedRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private ServiceReportRecorderRepository serviceReportRecorderRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private ReportRedDotRepository reportRedDotRepository;

    @Autowired
    private CustomerRegularReportRepository customerRegularReportRepository;

    @Autowired
    private AliSmsProvider aliSmsProvider;

    @Autowired
    private UserLogService userLogService;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserAdminService userAdminService;

    private static final Logger logger = LoggerFactory.getLogger(StationServiceReportServiceImpl.class);


    /////////////////////////////////////改/////////////////////////////////////////////////////////////////

    @Override
    public JsonResponse getCompleteReport(Long reportId) {
        QStationRegularServiceReport qStationRegularServiceReport = QStationRegularServiceReport.stationRegularServiceReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationRegularServiceReport.deleted.eq(false));
        builder.and(qStationRegularServiceReport.enabled.eq(true));
        builder.and(qStationRegularServiceReport.stationReport.id.eq(reportId));
        List<StationRegularServiceReport> regularServiceReports = (List<StationRegularServiceReport>) stationRegularServiceReportRepository.findAll(builder);
        return JsonResponse.successResponseWithData(regularServiceReports);
    }

    @Override
    public JsonResponse getUnFinshedReport(Long reportId) {
        QStationRegularServiceReportUnFinshed qStationRegularServiceReportUnFinshed = QStationRegularServiceReportUnFinshed.stationRegularServiceReportUnFinshed;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationRegularServiceReportUnFinshed.deleted.eq(false));
        builder.and(qStationRegularServiceReportUnFinshed.enabled.eq(true));
        builder.and(qStationRegularServiceReportUnFinshed.stationReportTemp.id.eq(reportId));
        List<StationRegularServiceReportUnFinshed> regularServiceReports = (List<StationRegularServiceReportUnFinshed>) stationRegularServiceReportUnFinshedRepository.findAll(builder);
        return JsonResponse.successResponseWithData(regularServiceReports);
    }


    /**
     * 管理员获取部门待处理-改
     */
    @Override
    public JsonResponse getDeparmentPending(Pageable pageable, String province, String city, String brand, String category, String stationName, Long stationId, Long serviceStartTime, Long serviceEndTime,
                                            Long starTime, Long endTime, Integer serviceNum, String serviceType, Boolean type, String score,String stationNum,String department,String payService,
                                            String sentTime,String serviceTime,String userName,String customerStat,String customerType,String paintBrand,String productPosition,Integer status) {
        Page<TechColorAuditingReports> page = null;
        String[] provinces = null;
        String[] cities = null;
        String[] categories = null;
        String[] brands = null;
        String[] serviceTypes = null;
        String[] departments = null;
        Long[] customerStats = null;
        Long[] customerTypes = null;
        String[] paintBrands = null;
        String[] productPositions = null;

        if (!StringUtils.isEmpty(province)) {
            provinces = province.split(",");
        }
        if (!StringUtils.isEmpty(city)) {
            cities = city.split(",");
        }
        if (!StringUtils.isEmpty(category)) {
            categories = category.split(",");
        }
        if (!StringUtils.isEmpty(brand)) {
            brands = brand.split(",");
        }
        if (!StringUtils.isEmpty(serviceType)){
            serviceTypes = serviceType.split(",");
        }
        if (!StringUtils.isEmpty(department)){
            departments = department.split(",");
        }

        if (!StringUtils.isEmpty(paintBrand)){
            paintBrands = paintBrand.split(",");
        }
        if (!StringUtils.isEmpty(productPosition)){
            productPositions = productPosition.split(",");
        }
        if (!StringUtils.isEmpty(customerStat)){
            customerStats = (Long[]) ConvertUtils.convert(customerStat.split(","),Long.class);
        }
        if (!StringUtils.isEmpty(customerType)){
            customerTypes = (Long[]) ConvertUtils.convert(customerType.split(","),Long.class);
        }

        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));

        builder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
        builder.and(qStationReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
        builder.and(qStationReport.specifiedType.isNotNull());
        if (status != null) {
            if (status == 0) {
                builder.and(qStationReport.specifiedType.eq(Constants.MANAGE_DEPARTMENT_UNREAD));
            } else if (status == 1) {
                builder.and(qStationReport.specifiedType.eq(Constants.MANAGE_DEPARTMENT_EDIT));
            } else if (status == 2) {
                builder.and(qStationReport.specifiedType.eq(Constants.MANAGE_DEPARTMENT_READ));
            }
        }
        if (customerStats != null) {
            builder.and(qStationReport.station.customerStat.in(customerStats));
        }
        if (customerTypes != null) {
            builder.and(qStationReport.station.customerType.in(customerTypes));
        }
        if (stationId != null && stationId != 0) {
            builder.and(qStationReport.station.id.eq(stationId));
        }
        if (StringUtils.isNotEmpty(province)) {
            builder.and(qStationReport.station.province.in(provinces));
        }
        if (StringUtils.isNotEmpty(city)) {
            builder.and(qStationReport.station.city.in(cities));
        }
        if (paintBrands!=null) {
            BooleanBuilder paintBrandBuilder = new BooleanBuilder();
            for (String pBrand:paintBrands){
                paintBrandBuilder.or(qStationReport.station.paintBrand.like("%" + pBrand + "%"));
            }
            builder.and(paintBrandBuilder);
        }
        if (productPositions!=null) {
            BooleanBuilder ppBuilder = new BooleanBuilder();
            for (String pp:productPositions){
                ppBuilder.or(qStationReport.station.productPosition.like("%" + pp + "%"));
            }
            builder.and(ppBuilder);
        }
        if (StringUtils.isNotEmpty(brand)) {
            BooleanBuilder builderOr = new BooleanBuilder();
            for (String brandStr: brands){
                builderOr.or(qStationReport.station.brand.like("%"+brandStr+"%"));
            }
            builder.and(builderOr);
        }
        if (categories != null) {
            builder.and(qStationReport.station.category.in(categories));
        }
        if (StringUtils.isNotEmpty(stationName)) {
            builder.and(qStationReport.station.name.like("%" + stationName + "%"));
        }
        if (StringUtils.isNotEmpty(stationNum)) {
            builder.and(qStationReport.station.stationNum.eq(stationNum));
        }
        if (starTime != null && starTime != 0 && endTime != null && endTime != 0) {
            builder.and(qStationReport.creationTime.after(new Date(starTime)));
            builder.and(qStationReport.creationTime.before(new Date(endTime)));
        }
        if (serviceStartTime != null && serviceStartTime != 0 && serviceEndTime != null && serviceEndTime != 0) {
            builder.and(qStationReport.startServiceTime.after(new Date(serviceStartTime)));
            builder.and(qStationReport.endServiceTime.before(new Date(serviceEndTime)));
        }
        if (serviceNum != null && serviceNum != 0) {
            builder.and(qStationReport.user.serviceNum.eq(serviceNum));
        }
        //查询服务项目
        if (serviceTypes != null) {
            //先从报告答案中找出所有填写过ids中任何一个id的答案
            QStationRegularServiceReport qStationRegularServiceReport = QStationRegularServiceReport.stationRegularServiceReport;
            BooleanBuilder regularBuilder = new BooleanBuilder();
            regularBuilder.and(qStationRegularServiceReport.deleted.eq(false));
            regularBuilder.and(qStationRegularServiceReport.enabled.eq(true));
            BooleanBuilder builderOr = new BooleanBuilder();
            for (String id:serviceTypes){
                builderOr.or(qStationRegularServiceReport.answerId.like("%"+id+"%"));
            }
            regularBuilder.and(builderOr);
            List<StationRegularServiceReport> list = (List<StationRegularServiceReport>) stationRegularServiceReportRepository.findAll(builderOr);
            if (list == null || list.size()==0){
                return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
            }
            //获取答案针对的报告站点报告id合集
            Long[] reportIDs = new Long[list.size()];
            for (int i=0;i<list.size();i++){
                reportIDs[i] = list.get(i).getStationReport().getId();
            }
            builder.and(qStationReport.id.in(reportIDs));
        }
        if (StringUtils.isNotEmpty(userName) || departments != null) {
            QStationColorReport qStationColorReport = QStationColorReport.stationColorReport;
            QUserProfile qUserProfile = QUserProfile.userProfile;
            BooleanBuilder booleanBuilder = new BooleanBuilder();
            booleanBuilder.and(qUserProfile.deleted.eq(false));
            booleanBuilder.and(qUserProfile.enabled.eq(true));
            booleanBuilder.and(qUserProfile.user.userFlag.in(0,2));
            boolean flag = false;
            if (StringUtils.isNotEmpty(userName)) {
                flag = true;
                booleanBuilder.and(qUserProfile.realName.like("%" + userName + "%"));
            }
            if (departments != null){
                flag = true;
                booleanBuilder.and(qUserProfile.user.userFlag.in(0,2));
                booleanBuilder.and(qUserProfile.user.userType.in(UserType.admin,UserType.dealers,UserType.insiders));
                for (String str:departments){
                    booleanBuilder.or(qUserProfile.departmentList.any().name.eq(str));
                }
            }
            if (flag) {
                List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(booleanBuilder);
                if (userProfileList == null || userProfileList.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> userIds = new ArrayList<>();
                for (UserProfile user : userProfileList) {
                    userIds.add(user.getUser().getId());
                }
                BooleanBuilder colorBuilder = new BooleanBuilder();
                colorBuilder.and(qStationColorReport.deleted.eq(false));
                colorBuilder.and(qStationColorReport.enabled.eq(true));
                colorBuilder.and(qStationColorReport.stationReport.station.report_finished.in(1, 2, 3));
                colorBuilder.and(qStationColorReport.stationReport.user.id.in(userIds));
                List<StationColorReport> list = (List<StationColorReport>) stationColorReportRepository.findAll(colorBuilder);
                if (list == null || list.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> ids = new ArrayList<>();
                for (StationColorReport report : list) {
                    if (report.getReportId() != null) {
                        ids.add(Long.parseLong(report.getReportId()));
                    }
                }
                builder.and(qStationReport.id.in(ids));
            }
        }
        if (payService != null || sentTime!=null || serviceTime!=null){
            QStationColorReport qStationColorReport = QStationColorReport.stationColorReport;
            BooleanBuilder builderStationColor = new BooleanBuilder();
            builderStationColor.and(qStationColorReport.deleted.eq(false));
            builderStationColor.and(qStationColorReport.enabled.eq(true));
            boolean flag = false;
            if (payService!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+payService+"%"));
            }
            if (sentTime!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+sentTime+"%"));
            }
            if (serviceTime!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+serviceTime+"%"));
            }
            if (flag) {
                List<StationColorReport> stationColorReports = (List<StationColorReport>) stationColorReportRepository.findAll(builderStationColor);
                if (stationColorReports == null || stationColorReports.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> Ids = new ArrayList<>();
                for (StationColorReport report : stationColorReports) {
                    Ids.add(report.getStationReport().getStation().getId());
                }
                builder.and(qStationReport.station.id.in(Ids));
            }
        }
        if (StringUtils.isNotEmpty(score)) {
            QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
            BooleanBuilder builderCustomer = new BooleanBuilder();
            builderCustomer.and(qCustomerRegularReport.deleted.eq(false));
            builderCustomer.and(qCustomerRegularReport.enabled.eq(true));
            String[] str = new String[61];
            for (int i = 0; i < str.length; i++) {
                str[i] = i + "";
            }
            String[] notStr = new String[39];
            int index = 61;
            for (int i = 0; i < 39; i++) {
                notStr[i] = index + "";
                index += 1;
            }
            if (score.equals(Constants.FULL_MARKS)) {
                builderCustomer.and(qCustomerRegularReport.score.eq("100"));
            }
            if (score.equals(Constants.MORE_THAN_SIXTY)) {
                builderCustomer.and(qCustomerRegularReport.score.in(notStr));
            }
            if (score.equals(Constants.BELOW_THAN_SIXTY)) {
                builderCustomer.and(qCustomerRegularReport.score.in(str));
            }
            List<CustomerRegularReport> list = (List<CustomerRegularReport>) customerRegularReportRepository.findAll(builderCustomer);
            if (list == null || list.size()==0){
                return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
            }
            Long[] reportIDs = new Long[list.size()];
            for (int i=0;i<list.size();i++){
                reportIDs[i] = list.get(i).getCustomerReport().getId();
            }
            builder.and(qStationReport.id.in(reportIDs));

        }
        if (type != null) {
            QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
            BooleanBuilder builderCustomer = new BooleanBuilder();
            builderCustomer.and(qCustomerRegularReport.deleted.eq(false));
            builderCustomer.and(qCustomerRegularReport.enabled.eq(true));
            builderCustomer.and(qCustomerRegularReport.type.eq(type));
            List<CustomerRegularReport> customerRegularReports = (List<CustomerRegularReport>) customerRegularReportRepository.findAll(builderCustomer);
            if (customerRegularReports == null || customerRegularReports.size()==0){
                return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
            }
            Long[] ids = new Long[customerRegularReports.size()];
            for (int i = 0; i < customerRegularReports.size(); i++) {
                ids[i] = customerRegularReports.get(i).getRegularReport().getId();
            }
            builder.and(qStationReport.id.in(ids));
        }
        Page<StationReport> stationReportList = stationReportRepository.findAll(builder,pageable);
        if (stationReportList==null){
            return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
        }else{
            Sort sort = new Sort(Sort.Direction.DESC, "creationTime");
            pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
            List<TechColorAuditingReports> responseList = toResponseVO(stationReportList.getContent());
            page = new PageImpl(responseList, pageable, stationReportList.getTotalElements());
            return JsonResponse.successResponseWithPageData(page);
        }
    }

    @Override
    public JsonResponse editDepartmentHead(User user, Long reportId, String deparmentIds) {
        if (StringUtils.isEmpty(deparmentIds)) {
            return JsonResponse.errorResponseWithError("抱歉", "请选择跟进部门");
        }
        StationReport stationReport = stationReportRepository.findOne(reportId);
        if (stationReport == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此报告");
        }
        String oldDepartmentIds = "";
        if (StringUtils.isNotEmpty(stationReport.getDeparmentIds())) {
            oldDepartmentIds = stationReport.getDeparmentIds();
        } else {
            return sureDeparmentHead(user, reportId, deparmentIds, null);
        }
        if (oldDepartmentIds.equals(deparmentIds)) {
            return JsonResponse.successResponse();
        }
        String[] oldIds = oldDepartmentIds.split(",");
        String[] newIds = deparmentIds.split(",");
        List<Long> oldIdList = arrayToList(oldIds);
        List<Long> newIdList = arrayToList(newIds);
        newIdList.removeAll(oldIdList);
        for (Long id : newIdList) {

        }


        stationReport.setDeparmentIds(deparmentIds);
        stationReport.setSpecifiedType(Constants.DEPARMENT_PEDING);
        stationReportRepository.save(stationReport);
        return JsonResponse.successResponse();
    }


    private List<Long> arrayToList(String[] ids) {
        List<Long> idList = new ArrayList<>();
        for (String id : ids) {
            if (StringUtils.isNotEmpty(id)) {
                idList.add(Long.valueOf(id));
            }
        }
        return idList;
    }

    /**
     * 管理员确认指定负责人-改
     */
    @Override
    public JsonResponse sureDeparmentHead(User user, Long reportId, String deparmentIds, String note) {
        StationReport stationReport = stationReportRepository.findOne(reportId);
        if (stationReport == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此报告");
        }
        UserProfile profile = userProfileRepository.findByUserId(user.getId());
        String realName = "";
        if (profile != null && StringUtils.isNotEmpty(profile.getRealName())) {
            realName = profile.getRealName();
        }
        User u = stationReport.getUser();
        String userName = userProfileRepository.findByUserId(u.getId()).getRealName();
        String stationName = stationReport.getStation().getName();
        String[] serviceTypeIds = stationReport.getServiceTypAnswerIds().split(",");
        StringBuffer stringBuffer = new StringBuffer("");
        for (String id : serviceTypeIds) {
            if (StringUtils.isNotEmpty(id)) {
                if (id.equals("191")) {
                    stringBuffer.append("漆星服务");
                    break;
                } else {
                    QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                    if (answerOption != null&& answerOption.getName()!=null) {
                        stringBuffer.append(answerOption.getName() + ",");
                    }
                }
            }
        }
        StringBuffer departmentBffer = new StringBuffer("");
        if (StringUtils.isNotEmpty(deparmentIds)) {
            String[] ids = deparmentIds.split(",");
            for (String id : ids) {
                if (StringUtils.isNotEmpty(id)) {
                    Department department = departmentRepository.findOne(Long.valueOf(id));
                    if (department != null && StringUtils.isNotEmpty(department.getTotalName())) {
                        departmentBffer.append(department.getTotalName() + ",");
                    }
                }
            }
        }
        try {
            Date date = new Date();
            stationReport.setDeparmentIds(deparmentIds);
            //负责人的状态
            stationReport.setExceptionType(Constants.DEPARTMENT_UNREAD);
            //管理员的状态
            stationReport.setSpecifiedType(Constants.MANAGE_DEPARTMENT_READ);
            stationReport.setAdminReaded(true);
            stationReport.setUpdateTime(date);
            stationReport.setUpdateTimeStr(new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT).format(date));
            stationReport.setEditUser(user);
            stationReportRepository.save(stationReport);
            List<UserProfile> userProfileList = new ArrayList<>();
            StringBuffer departmentBuffer = new StringBuffer();
            String[] ids = deparmentIds.split(",");
            ServiceReportRecorder reportRecorder = new ServiceReportRecorder();
            reportRecorder.setStationReport(stationReport);
            reportRecorder.setNote("确认的部门为：" + departmentBffer.toString());
            reportRecorder.setNeedFollowDepartment(departmentBffer.toString());
            reportRecorder.setType(Constants.MANAGE_DEPARTMENT_READ);
            reportRecorder.setUser(user);
            if (StringUtils.isNotEmpty(note)) {
                reportRecorder.setManageNote("备注：" + note);
            }
            serviceReportRecorderRepository.save(reportRecorder);
            //添加日志
            userLogService.addUserLog(user, stationReport.getStation().getStationNum(), stationReport.getId(), Constants.SERVICE_REPORT, LogConstants.operate_type_confirm,
                    LogConstants.business_type_regular_report, null, null);
            for (String str : ids) {
                Department department = departmentRepository.findOne(Long.valueOf(str));
                if (department != null) {
                    departmentBuffer.append(department.getTotalName() + ",");
                }
                QReportRedDot qReportRedDot = QReportRedDot.reportRedDot;
                BooleanBuilder dotbuilder = new BooleanBuilder();
                dotbuilder.and(qReportRedDot.deleted.eq(false));
                dotbuilder.and(qReportRedDot.enabled.eq(true));
                dotbuilder.and(qReportRedDot.departmentId.eq(Long.valueOf(str)));
                dotbuilder.and(qReportRedDot.stationReport.id.eq(stationReport.getId()));
                ReportRedDot redDot = reportRedDotRepository.findOne(dotbuilder);
                if (null == redDot) {
                    redDot = new ReportRedDot();
                    redDot.setStationReport(stationReport);
                    redDot.setDepartmentId(Long.valueOf(str));
                    redDot.setNote(note);
                    redDot.setIsSendMsg(0);
                    //首次创建部门待处理的话 将报告的创建者设置进去 以便后面区分
                    redDot.setUser(u);
                    redDot.setType(Constants.DEPARTMENT_UNREAD);
                } else {
                    redDot.setReaded(false);
                    redDot.setIsSendMsg(0);
                    redDot.setType(Constants.DEPARTMENT_UNREAD);
                    redDot.setNote(note);
                }
                reportRedDotRepository.save(redDot);

                QUserProfile qUserProfile = QUserProfile.userProfile;
                BooleanBuilder builder = new BooleanBuilder();
                builder.and(qUserProfile.deleted.eq(false));
                builder.and(qUserProfile.enabled.eq(true));
                builder.and(qUserProfile.departmentList.any().id.eq(Long.valueOf(str)));
                List<UserProfile> userProfiles = (List<UserProfile>) userProfileRepository.findAll(builder);
                for (UserProfile userProfile : userProfiles) {
                    userProfileList.add(userProfile);
                }
            }
            Map<String, Integer> userMap = new HashMap<>();
            Map<User, Integer> msgUserMap = new HashMap<>();
            for (UserProfile userProfile : userProfileList) {
                String telephone = userProfile.getTelephone();
                if (userMap.containsKey(telephone)) {
                    continue;
                } else {
                    userMap.put(telephone, 1);
                }
                if (msgUserMap.containsKey(userProfile.getUser())) {
                    continue;
                } else {
                    msgUserMap.put(userProfile.getUser(), 1);
                }

            }
            //发送短信通知所选部门下的所有人
            StringBuffer stringBufferUser = new StringBuffer("");
            for (Map.Entry<String, Integer> entry : userMap.entrySet()) {
                String telephone = entry.getKey();
                stringBufferUser.append(telephone + ",");
            }

            try {
                logger.info("---------------------------开始发送短息----------------------");
                logger.info("发送的手机号码为：" + stringBufferUser);
                logger.info("创建报告者：" + userName);
                logger.info("维修站名称:" + stationName);
                logger.info("服务项目为:" + stringBuffer);
                logger.info("部门为:" + departmentBuffer);
                String serviceStr = stringBuffer.toString();
                if (!serviceStr.equals("漆星服务")) {
                    serviceStr = serviceStr.substring(0, serviceStr.length() - 1);
                }
                String departmentStr = departmentBuffer.toString();
                if (StringUtils.isNotEmpty(departmentBuffer.toString())) {
                    departmentStr = departmentStr.substring(0, departmentBuffer.toString().length() - 1);
                }
                aliSmsProvider.sendSureDepartment(stringBufferUser.toString(), userName, stationName,
                        serviceStr, departmentStr);
                logger.info("---------------------------短信发送成功---------------------------");
                logger.info("---------------------------开始推送微信---------------------------");
                String firstData = "您好，在" + stationName + "进行的" + stringBuffer.toString() + "需要" + departmentStr + "跟进";
                for (Map.Entry<User, Integer> msgUser : msgUserMap.entrySet()) {
                    wechatService.pushWechatMessage(msgUser.getKey(), "Ujk2bjdBKx3vU1IjSH3OyD84rgF0Hz-oU2Ds564DW2I", Constants.WECHAT_PUSH_URL, firstData,
                            "请尽快登录漆星服务系统进行项目认领跟进", userName, stationReport.getUpdateTimeStr(), "", "", "");
                }
                logger.info("---------------------------推送微信成功---------------------------");
            } catch (Exception e) {
                return JsonResponse.errorResponseWithError("抱歉", "发送短信失败");
            }
            return JsonResponse.successResponse();
        } catch (Exception e) {
            return JsonResponse.errorResponseWithError("抱歉", "处理失败");
        }
    }

    /**
     * 管理员保存确认的指定部门-改
     */
    @Override
    public JsonResponse saveDeparmentHead(User user, Long reportId, String deparmentIds) {
        StationReport stationReport = stationReportRepository.findOne(reportId);
        if (stationReport == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此报告");
        }
        stationReport.setDeparmentIds(deparmentIds);
        try {
            stationReportRepository.save(stationReport);
            return JsonResponse.successResponse();
        } catch (Exception e) {
            return JsonResponse.errorResponseWithError("抱歉", "处理失败");
        }
    }

    /**
     * 管理员获取需要其他部门跟进的报告
     */
    @Override
    public JsonResponse getEditDepartmentReport(User user, String province, String city, String brand, String category, String stationName,
                                                String useraName, Pageable pageable) {
        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
        builder.and(qStationReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
        builder.and(qStationReport.specifiedType.eq(Constants.MANAGE_DEPARTMENT_EDIT));
        if (StringUtils.isNotEmpty(province)) {
            String[] provinceArray = province.split(",");
            builder.and(qStationReport.station.province.in(provinceArray));
        }
        if (StringUtils.isNotEmpty(city)) {
            builder.and(qStationReport.station.city.eq(city));
        }
        if (StringUtils.isNotEmpty(brand)) {
            String[] brandArray = brand.split(",");
            BooleanBuilder orBuilder = new BooleanBuilder();
            for (int i = 0; i < brandArray.length; i++) {
                orBuilder.or(qStationReport.station.brand.like("%" + brandArray[i] + "%"));
            }
            builder.and(orBuilder);
        }
        if (StringUtils.isNotEmpty(category)) {
            builder.and(qStationReport.station.category.eq(category));
        }
        if (StringUtils.isNotEmpty(stationName)) {
            builder.and(qStationReport.station.name.like("%" + stationName + "%"));
        }
        if (StringUtils.isNotEmpty(useraName)) {
            QUserProfile qUserProfile = QUserProfile.userProfile;
            BooleanBuilder booleanBuilder = new BooleanBuilder();
            booleanBuilder.and(qUserProfile.deleted.eq(false));
            booleanBuilder.and(qUserProfile.enabled.eq(true));
            booleanBuilder.and(qUserProfile.realName.like("%" + useraName + "%"));
            List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(booleanBuilder);
            List<Long> userIds = new ArrayList<>();
            for (UserProfile u : userProfileList) {
                userIds.add(u.getUser().getId());
            }
            builder.and(qStationReport.user.id.in(userIds));
        }
        Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<StationReport> stationReportPage = stationReportRepository.findAll(builder, pageable);
        List<TechColorAuditingReports> colorAuditingReports = toResponseVO(stationReportPage.getContent());
        Page<TechColorAuditingReports> page = new PageImpl(colorAuditingReports, pageable, stationReportPage.getTotalElements());
        return JsonResponse.successResponseWithPageData(page);
    }

    /**
     * 管理员获得已经确认的报告-改
     */
    @Override
    public JsonResponse getSureDeparmentHead(Pageable pageable, Long stationId, Long serviceStartTime, Long serviceEndTime,
                                             Long starTime, Long endTime, Long userId, Integer serviceNum, Long answerId, Boolean type, String score, String reportType) {
        QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qCustomerRegularReport.deleted.eq(false));
//        builder.and(qCustomerRegularReport.enabled.eq(true));
        builder.and(qCustomerRegularReport.regularReport.category.eq(Constants.SERVICE_REPORT));
        builder.and(qCustomerRegularReport.regularReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
        builder.and(qCustomerRegularReport.regularReport.specifiedType.eq(Constants.MANAGE_DEPARTMENT_READ));
        if (stationId != null && stationId != 0) {
            builder.and(qCustomerRegularReport.regularReport.station.id.eq(stationId));
        }
        if (starTime != null && starTime != 0 && endTime != null && endTime != 0) {
            builder.and(qCustomerRegularReport.regularReport.creationTime.after(new Date(starTime)));
            builder.and(qCustomerRegularReport.regularReport.creationTime.before(new Date(endTime)));
        }
        if (serviceStartTime != null && serviceStartTime != 0 && serviceEndTime != null && serviceEndTime != 0) {
            builder.and(qCustomerRegularReport.regularReport.startServiceTime.after(new Date(serviceStartTime)));
            builder.and(qCustomerRegularReport.regularReport.endServiceTime.before(new Date(serviceEndTime)));
        }
        if (userId != null && userId != 0) {
            builder.and(qCustomerRegularReport.regularReport.user.id.eq(userId));
        }
        if (serviceNum != null && serviceNum != 0) {
            builder.and(qCustomerRegularReport.regularReport.user.serviceNum.eq(serviceNum));
        }
        if (answerId != null && answerId != 0) {
            builder.and(qCustomerRegularReport.regularReport.serviceTypAnswerIds.like("%" + answerId + "%"));
        }
        if (type != null) {
            builder.and(qCustomerRegularReport.type.eq(type));
        }
        if (StringUtils.isNotEmpty(reportType)) {
            builder.and(qCustomerRegularReport.type);
        }
        if (StringUtils.isNotEmpty(score)) {
            if (score.equals("满分")) {
                builder.and(qCustomerRegularReport.score.eq("100.0"));
            }
            if (score.equals("60分以上")) {
                builder.and(qCustomerRegularReport.score.gt("60.0"));
            }
            if (score.equals("60分以下")) {
                builder.and(qCustomerRegularReport.score.lt("60.0"));
            }
        }
        Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<CustomerRegularReport> customerRegularReports = customerRegularReportRepository.findAll(builder, pageable);
        List<StationReport> stationReportList = new ArrayList<>();
        if (StringUtils.isNotEmpty(reportType)) {
            QServiceReportRecorder qServiceReportRecorder = QServiceReportRecorder.serviceReportRecorder;
            BooleanBuilder serviceBuilder = new BooleanBuilder();
            for (CustomerRegularReport customerRegularReport : customerRegularReports) {
                serviceBuilder = new BooleanBuilder();
                serviceBuilder.and(qServiceReportRecorder.deleted.eq(false));
                serviceBuilder.and(qServiceReportRecorder.enabled.eq(true));
                serviceBuilder.and(qServiceReportRecorder.stationReport.id.eq(customerRegularReport.getRegularReport().getId()));
                if (reportType.equals("全部未介入")) {
                    serviceBuilder.and(qServiceReportRecorder.type.eq(Constants.REPORT_PLAN));
                }
                if (reportType.equals("全部已中断")) {
                    serviceBuilder.and(qServiceReportRecorder.type.eq(Constants.REPORT_INTERRUPT));
                }
                sort = new Sort(Sort.Direction.DESC, "creationTime");
                pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
                List<ServiceReportRecorder> serviceReportRecorderList = (List<ServiceReportRecorder>) serviceReportRecorderRepository.findAll(serviceBuilder);

                if (reportType.equals("全部未介入") || reportType.equals("全部已中断")) {
                    try {
                        if (serviceReportRecorderList.size() == customerRegularReport.getRegularReport().getDeparmentIds().length()) {
                            stationReportList.add(customerRegularReport.getRegularReport());
                        } else {
                            continue;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                }

                for (ServiceReportRecorder reportRecorder : serviceReportRecorderList) {
                    if (reportType.equals("有部门跟进中") && reportRecorder.getType().equals(Constants.REPORT_FOLLOWUP)) {
                        stationReportList.add(customerRegularReport.getRegularReport());
                        continue;
                    }
                    if (reportType.equals("有部门已中断") && reportRecorder.getType().equals(Constants.REPORT_INTERRUPT)) {
                        stationReportList.add(customerRegularReport.getRegularReport());
                        continue;
                    }
                }

            }
            List<TechColorAuditingReports> responseList = toResponseVO(stationReportList);
            Page<TechColorAuditingReports> page = new PageImpl(responseList, pageable, customerRegularReports.getTotalElements());
            return JsonResponse.successResponseWithPageData(page);
        }

        for (CustomerRegularReport customerRegularReport : customerRegularReports) {
            stationReportList.add(customerRegularReport.getRegularReport());
        }
        List<TechColorAuditingReports> responseList = toResponseVO(stationReportList);

        Page<TechColorAuditingReports> page = new PageImpl(responseList, pageable, customerRegularReports.getTotalElements());
        return JsonResponse.successResponseWithPageData(page);

    }

    /**
     * 部门获取被指定的报告-改
     */
    @Override
    public JsonResponse headGetReport(User user, Pageable pageable, String province, String city, String brand, String category, String stationName, Long stationId, Long serviceStartTime, Long serviceEndTime,
                                      Long starTime, Long endTime, Integer serviceNum, String serviceType, Boolean type, String score,String stationNum,String department,String payService,
                                      String sentTime,String serviceTime,String userName,String customerStat,String customerType,String paintBrand,String productPosition) {
        UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
        if (userProfile == null) {
            return JsonResponse.errorResponseWithError("抱歉", "当前用户信息不全");
        }
        List<Department> departments = userProfile.getDepartmentList();
        if (departments == null || departments.size() == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "当前用户没有绑定部门");
        }
        List<Long> idList = new ArrayList<>();
        for (Department d : departments) {
            if (d.getName().equals("经销商") || d.getName().equals("销售部")
                    || d.getName().equals("技术部") || d.getName().equals("市场部") || d.getName().equals("物流部")
                    || d.getName().equals("颜色部")) {
                List<Department> departmentList = departmentRepository.selectParentDeparmentL(d.getId());
                for (Department de : departmentList) {
                    idList.add(de.getId());
                }
            }
            idList.add(d.getId());
        }

        String[] provinces = null;
        String[] cities = null;
        String[] categories = null;
        String[] brands = null;
        String[] serviceTypes = null;
        String[] departmentIDs = null;
        Long[] customerStats = null;
        Long[] customerTypes = null;
        String[] paintBrands = null;
        String[] productPositions = null;

        if (!StringUtils.isEmpty(province)) {
            provinces = province.split(",");
        }
        if (!StringUtils.isEmpty(city)) {
            cities = city.split(",");
        }
        if (!StringUtils.isEmpty(category)) {
            categories = category.split(",");
        }
        if (!StringUtils.isEmpty(brand)) {
            brands = brand.split(",");
        }
        if (!StringUtils.isEmpty(serviceType)){
            serviceTypes = serviceType.split(",");
        }
        if (!StringUtils.isEmpty(department)){
            departmentIDs = department.split(",");
        }

        if (!StringUtils.isEmpty(paintBrand)){
            paintBrands = paintBrand.split(",");
        }
        if (!StringUtils.isEmpty(productPosition)){
            productPositions = productPosition.split(",");
        }
        if (!StringUtils.isEmpty(customerStat)){
            customerStats = (Long[]) ConvertUtils.convert(customerStat.split(","),Long.class);
        }
        if (!StringUtils.isEmpty(customerType)){
            customerTypes = (Long[]) ConvertUtils.convert(customerType.split(","),Long.class);
        }



        QReportRedDot qReportRedDot = QReportRedDot.reportRedDot;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qReportRedDot.deleted.eq(false));
        builder.and(qReportRedDot.enabled.eq(true));
        if (!idList.isEmpty()) {
            builder.and(qReportRedDot.departmentId.in(idList));
        }
        builder.and(qReportRedDot.type.eq(Constants.DEPARTMENT_UNREAD));
        if (customerStats != null) {
            builder.and(qReportRedDot.stationReport.station.customerStat.in(customerStats));
        }
        if (customerTypes != null) {
            builder.and(qReportRedDot.stationReport.station.customerType.in(customerTypes));
        }
        if (stationId != null && stationId != 0) {
            builder.and(qReportRedDot.stationReport.station.id.eq(stationId));
        }
        if (StringUtils.isNotEmpty(province)) {
            builder.and(qReportRedDot.stationReport.station.province.in(provinces));
        }
        if (StringUtils.isNotEmpty(city)) {
            builder.and(qReportRedDot.stationReport.station.city.in(cities));
        }
        if (paintBrands!=null) {
            BooleanBuilder paintBrandBuilder = new BooleanBuilder();
            for (String pBrand:paintBrands){
                paintBrandBuilder.or(qReportRedDot.stationReport.station.paintBrand.like("%" + pBrand + "%"));
            }
            builder.and(paintBrandBuilder);
        }
        if (productPositions!=null) {
            BooleanBuilder ppBuilder = new BooleanBuilder();
            for (String pp:productPositions){
                ppBuilder.or(qReportRedDot.stationReport.station.productPosition.like("%" + pp + "%"));
            }
            builder.and(ppBuilder);
        }
        if (StringUtils.isNotEmpty(brand)) {
            BooleanBuilder builderOr = new BooleanBuilder();
            for (String brandStr: brands){
                builderOr.or(qReportRedDot.stationReport.station.brand.like("%"+brandStr+"%"));
            }
            builder.and(builderOr);
        }
        if (categories != null) {
            builder.and(qReportRedDot.stationReport.station.category.in(categories));
        }
        if (StringUtils.isNotEmpty(stationName)) {
            builder.and(qReportRedDot.stationReport.station.name.like("%" + stationName + "%"));
        }
        if (StringUtils.isNotEmpty(stationNum)) {
            builder.and(qReportRedDot.stationReport.station.stationNum.eq(stationNum));
        }
        if (starTime != null && starTime != 0 && endTime != null && endTime != 0) {
            builder.and(qReportRedDot.stationReport.creationTime.after(new Date(starTime)));
            builder.and(qReportRedDot.stationReport.creationTime.before(new Date(endTime)));
        }
        if (serviceStartTime != null && serviceStartTime != 0 && serviceEndTime != null && serviceEndTime != 0) {
            builder.and(qReportRedDot.stationReport.startServiceTime.after(new Date(serviceStartTime)));
            builder.and(qReportRedDot.stationReport.endServiceTime.before(new Date(serviceEndTime)));
        }
        if (serviceNum != null && serviceNum != 0) {
            builder.and(qReportRedDot.stationReport.user.serviceNum.eq(serviceNum));
        }
        //查询服务项目
        if (serviceTypes != null) {
            //先从报告答案中找出所有填写过ids中任何一个id的答案
            QStationRegularServiceReport qStationRegularServiceReport = QStationRegularServiceReport.stationRegularServiceReport;
            BooleanBuilder regularBuilder = new BooleanBuilder();
            regularBuilder.and(qStationRegularServiceReport.deleted.eq(false));
            regularBuilder.and(qStationRegularServiceReport.enabled.eq(true));
            BooleanBuilder builderOr = new BooleanBuilder();
            for (String id:serviceTypes){
                builderOr.or(qStationRegularServiceReport.answerId.like("%"+id+"%"));
            }
            regularBuilder.and(builderOr);
            List<StationRegularServiceReport> list = (List<StationRegularServiceReport>) stationRegularServiceReportRepository.findAll(builderOr);
            if (list == null || list.size()==0){
                return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
            }
            //获取答案针对的报告站点报告id合集
            Long[] reportIDs = new Long[list.size()];
            for (int i=0;i<list.size();i++){
                reportIDs[i] = list.get(i).getStationReport().getId();
            }
            builder.and(qReportRedDot.stationReport.id.in(reportIDs));
        }
        if (StringUtils.isNotEmpty(userName) || departmentIDs != null) {
            QStationColorReport qStationColorReport = QStationColorReport.stationColorReport;
            QUserProfile qUserProfile = QUserProfile.userProfile;
            BooleanBuilder booleanBuilder = new BooleanBuilder();
            booleanBuilder.and(qUserProfile.deleted.eq(false));
            booleanBuilder.and(qUserProfile.enabled.eq(true));
            booleanBuilder.and(qUserProfile.user.userFlag.in(0,2));
            boolean flag = false;
            if (StringUtils.isNotEmpty(userName)) {
                flag = true;
                booleanBuilder.and(qUserProfile.realName.like("%" + userName + "%"));
            }
            if (departmentIDs != null){
                flag = true;
                booleanBuilder.and(qUserProfile.user.userFlag.in(0,2));
                booleanBuilder.and(qUserProfile.user.userType.in(UserType.admin,UserType.dealers,UserType.insiders));
                for (String str:departmentIDs){
                    booleanBuilder.or(qUserProfile.departmentList.any().name.eq(str));
                }
            }
            if (flag) {
                List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(booleanBuilder);
                if (userProfileList == null || userProfileList.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> userIds = new ArrayList<>();
                for (UserProfile user1 : userProfileList) {
                    userIds.add(user1.getUser().getId());
                }
                BooleanBuilder colorBuilder = new BooleanBuilder();
                colorBuilder.and(qStationColorReport.deleted.eq(false));
                colorBuilder.and(qStationColorReport.enabled.eq(true));
                colorBuilder.and(qStationColorReport.stationReport.station.report_finished.in(1, 2, 3));
                colorBuilder.and(qStationColorReport.stationReport.user.id.in(userIds));
                List<StationColorReport> list = (List<StationColorReport>) stationColorReportRepository.findAll(colorBuilder);
                if (list == null || list.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> ids = new ArrayList<>();
                for (StationColorReport report : list) {
                    if (report.getReportId() != null) {
                        ids.add(Long.parseLong(report.getReportId()));
                    }
                }
                builder.and(qReportRedDot.stationReport.id.in(ids));
            }
        }
        if (payService != null || sentTime!=null || serviceTime!=null){
            QStationColorReport qStationColorReport = QStationColorReport.stationColorReport;
            BooleanBuilder builderStationColor = new BooleanBuilder();
            builderStationColor.and(qStationColorReport.deleted.eq(false));
            builderStationColor.and(qStationColorReport.enabled.eq(true));
            boolean flag = false;
            if (payService!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+payService+"%"));
            }
            if (sentTime!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+sentTime+"%"));
            }
            if (serviceTime!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+serviceTime+"%"));
            }
            if (flag) {
                List<StationColorReport> stationColorReports = (List<StationColorReport>) stationColorReportRepository.findAll(builderStationColor);
                if (stationColorReports == null || stationColorReports.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> Ids = new ArrayList<>();
                for (StationColorReport report : stationColorReports) {
                    Ids.add(report.getStationReport().getStation().getId());
                }
                builder.and(qReportRedDot.stationReport.station.id.in(Ids));
            }
        }
        if (StringUtils.isNotEmpty(score)) {
            QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
            BooleanBuilder builderCustomer = new BooleanBuilder();
            builderCustomer.and(qCustomerRegularReport.deleted.eq(false));
            builderCustomer.and(qCustomerRegularReport.enabled.eq(true));
            String[] str = new String[61];
            for (int i = 0; i < str.length; i++) {
                str[i] = i + "";
            }
            String[] notStr = new String[39];
            int index = 61;
            for (int i = 0; i < 39; i++) {
                notStr[i] = index + "";
                index += 1;
            }
            if (score.equals(Constants.FULL_MARKS)) {
                builderCustomer.and(qCustomerRegularReport.score.eq("100"));
            }
            if (score.equals(Constants.MORE_THAN_SIXTY)) {
                builderCustomer.and(qCustomerRegularReport.score.in(notStr));
            }
            if (score.equals(Constants.BELOW_THAN_SIXTY)) {
                builderCustomer.and(qCustomerRegularReport.score.in(str));
            }
            List<CustomerRegularReport> list = (List<CustomerRegularReport>) customerRegularReportRepository.findAll(builderCustomer);
            if (list == null || list.size()==0){
                return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
            }
            Long[] reportIDs = new Long[list.size()];
            for (int i=0;i<list.size();i++){
                reportIDs[i] = list.get(i).getCustomerReport().getId();
            }
            builder.and(qReportRedDot.stationReport.id.in(reportIDs));

        }
        Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<ReportRedDot> redDots = reportRedDotRepository.findAll(builder, pageable);
        List<TechColorAuditingReports> responseList = toReportResponse(redDots.getContent());
        Page<TechColorAuditingReports> page = new PageImpl(responseList, pageable, redDots.getTotalElements());
        return JsonResponse.successResponseWithPageData(page);
    }


    /**
     * 部门处理被指定的报告-改
     */
    @Override
    public JsonResponse headManageReport(User user, Long reportId, String note, String type, Long departmentId, String departmentIds) {
        logger.info("headManageReport:reportId={}", reportId);
        logger.info("headManageReport:type={}", type);
        logger.info("headManageReport:departmentId={}", departmentId);
        logger.info("headManageReport:note={}", note);
        logger.info("headManageReport:departmentIds={}", departmentIds);
        StationReport stationReport = stationReportRepository.findOne(reportId);
        if (stationReport == null) {
            return JsonResponse.errorResponseWithError("200", "未找到此报告");
        }
        stationReport.setEditUser(user);
        //保存部门处理的状态
        stationReport.setExceptionType(type);
        String[] idArray = stationReport.getDeparmentIds().split(",");
        StringBuffer telephone = new StringBuffer("");
        for (String id : idArray) {
            QUserProfile qUserProfile = QUserProfile.userProfile;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qUserProfile.deleted.eq(false));
            builder.and(qUserProfile.enabled.eq(true));
            builder.and(qUserProfile.departmentList.any().id.eq(Long.valueOf(id)));
            List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(builder);
            for (UserProfile userProfile : userProfileList) {
                telephone.append(userProfile.getTelephone() + ",");
            }
        }
        StringBuffer departmentBuffer = new StringBuffer("");
        if (StringUtils.isNotEmpty(departmentIds) && type.equals(Constants.EDIT_DEPRTMENT)) {
            QReportRedDot qReportRedDot = QReportRedDot.reportRedDot;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qReportRedDot.deleted.eq(false));
            builder.and(qReportRedDot.enabled.eq(true));
            builder.and(qReportRedDot.departmentId.eq(departmentId));
            builder.and(qReportRedDot.stationReport.id.eq(reportId));
            builder.and(qReportRedDot.type.eq(Constants.DEPARTMENT_UNREAD));
            ReportRedDot redDot = reportRedDotRepository.findOne(builder);
            if (null == redDot) {
                return JsonResponse.errorResponseWithError("200", "请勿重复提交");
            }
            redDot.setUpdateTime(new Date());
            redDot.setType(type);
            redDot.setUser(user);
            redDot.setIsSendMsg(1);
            redDot.setReaded(true);
            reportRedDotRepository.save(redDot);
            String[] ids = departmentIds.split(",");
//            String[] oldIds = stationReport.getDeparmentIds().split(",");
            for (String id : ids) {
//                for (String old : oldIds) {
//                    if (id.equals(old)) {
//                        QReportRedDot qReportRedDot = QReportRedDot.reportRedDot;
//                        BooleanBuilder builder = new BooleanBuilder();
//                        builder.and(qReportRedDot.deleted.eq(false));
//                        builder.and(qReportRedDot.enabled.eq(true));
//                        builder.and(qReportRedDot.departmentId.eq(Long.valueOf(old)));
//                        builder.and(qReportRedDot.stationReport.id.eq(stationReport.getId()));
//                        ReportRedDot redDot = reportRedDotRepository.findOne(builder);
//                        if (redDot != null && redDot.getType().equals(Constants.DEPARTMENT_UNREAD)) {
//                            continue;
//                        }
//                        redDot.setType(Constants.DEPARTMENT_UNREAD);
//                        reportRedDotRepository.save(redDot);
//                    }
//                }
                if (StringUtils.isNotEmpty(id)) {
                    Department department = departmentRepository.findOne(Long.valueOf(id));
                    if (department != null && StringUtils.isNotEmpty(department.getTotalName())) {
                        departmentBuffer.append(department.getTotalName() + ",");
                    }
                }
            }
            stationReport.setDeparmentIds(departmentIds);
            stationReport.setSpecifiedType(Constants.MANAGE_DEPARTMENT_EDIT);
            stationReport.setUpdateTime(new Date());
            stationReport.setUpdateTimeStr(new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT).format(new Date()));
            stationReport.setEditUser(user);
            stationReportRepository.save(stationReport);
            ServiceReportRecorder reportRecorder = new ServiceReportRecorder();
            reportRecorder.setNeedFollowDepartment(departmentBuffer.toString());
            reportRecorder.setType(type);
            UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
            if (userProfile == null) {
                return JsonResponse.errorResponseWithError("抱歉", "未找到当前用户名称");
            }
            reportRecorder.setStationReport(stationReport);
            reportRecorder.setUser(user);
            Department department = departmentRepository.findOne(departmentId);
            if (department != null) {
                reportRecorder.setDepartment(department);
            }
//            String departmentName = department.getTotalName();
//            String userName = userProfile.getRealName();
            note = "备注：" + note;
            reportRecorder.setNote(note);
            serviceReportRecorderRepository.save(reportRecorder);
            //添加日志
            userLogService.addUserLog(user, stationReport.getStation().getStationNum(), stationReport.getId(), Constants.SERVICE_REPORT, type,
                    LogConstants.business_type_regular_report_edit, null, null);
            return updateMsg(user, telephone.toString(), stationReport, type, department);
        }
        ServiceReportRecorder reportRecorder = new ServiceReportRecorder();
        reportRecorder.setType(type);
        reportRecorder.setNote("备注：" + note);
        reportRecorder.setStationReport(stationReport);
        reportRecorder.setUser(user);
        reportRecorder.setNeedFollowDepartment(departmentBuffer.toString());
        Department department = departmentRepository.findOne(departmentId);
        if (department != null) {
            reportRecorder.setDepartment(department);
        }
        serviceReportRecorderRepository.save(reportRecorder);

        QReportRedDot qReportRedDot = QReportRedDot.reportRedDot;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qReportRedDot.deleted.eq(false));
        builder.and(qReportRedDot.enabled.eq(true));
        builder.and(qReportRedDot.departmentId.eq(departmentId));
        builder.and(qReportRedDot.stationReport.id.eq(reportId));
        builder.and(qReportRedDot.type.eq(Constants.DEPARTMENT_UNREAD));
        ReportRedDot redDot = reportRedDotRepository.findOne(builder);
        if (null != redDot) {
            redDot.setType(type);
            redDot.setIsSendMsg(1);
            redDot.setReaded(true);
            redDot.setUser(user);
            redDot.setUpdateTime(new Date());
            reportRedDotRepository.save(redDot);
        }
        try {
            //发送短信给部门下的所有人
            stationReportRepository.save(stationReport);
            //添加日志
            userLogService.addUserLog(user, stationReport.getStation().getStationNum(), stationReport.getId(), Constants.SERVICE_REPORT, type,
                    LogConstants.business_type_regular_report, null, null);
            return updateMsg(user, telephone.toString(), stationReport, type, department);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResponse.errorResponseWithError("500", "处理失败");
        }
    }

    //管理员二次处理被指定的报告-改
    @Override
    public JsonResponse updateHeadManageReport(User user, Long reportId, String note, String type, String oldType, Long departmentId, String departmentIds) {
        StationReport stationReport = stationReportRepository.findOne(reportId);
        if (stationReport == null) {
            return JsonResponse.errorResponseWithError("200", "未找到此报告");
        }
        stationReport.setEditUser(user);
        //保存部门处理的状态
        stationReport.setExceptionType(type);
        String[] idArray = stationReport.getDeparmentIds().split(",");
        StringBuffer telephone = new StringBuffer("");
        for (String id : idArray) {
            QUserProfile qUserProfile = QUserProfile.userProfile;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qUserProfile.deleted.eq(false));
            builder.and(qUserProfile.enabled.eq(true));
            builder.and(qUserProfile.departmentList.any().id.eq(Long.valueOf(id)));
            List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(builder);
            for (UserProfile userProfile : userProfileList) {
                telephone.append(userProfile.getTelephone() + ",");
            }
        }
        if (StringUtils.isNotEmpty(departmentIds) && type.equals(Constants.EDIT_DEPRTMENT)) {
            String[] ids = departmentIds.split(",");
            StringBuffer stringBuffer = new StringBuffer("");
//            String[] oldIds = stationReport.getDeparmentIds().split(",");
            for (String id : ids) {
//                for (String old : oldIds) {
//                    if (id.equals(old)) {
//                        QReportRedDot qReportRedDot = QReportRedDot.reportRedDot;
//                        BooleanBuilder builder = new BooleanBuilder();
//                        builder.and(qReportRedDot.deleted.eq(false));
//                        builder.and(qReportRedDot.enabled.eq(true));
//                        builder.and(qReportRedDot.departmentId.eq(Long.valueOf(old)));
//                        builder.and(qReportRedDot.stationReport.id.eq(stationReport.getId()));
////                        builder.and(qReportRedDot.type.ne(Constants.DEPARTMENT_UNREAD));
//                        ReportRedDot redDot = reportRedDotRepository.findOne(builder);
//                        if (redDot != null && redDot.getType().equals(Constants.DEPARTMENT_UNREAD)) {
//                            continue;
//                        }
//                        redDot.setType(Constants.DEPARTMENT_UNREAD);
//                        reportRedDotRepository.save(redDot);
////                        return JsonResponse.errorResponseWithError("抱歉", "目前暂不支持已经选择过的部门，敬请期待");
//                    }
//                }
                if (StringUtils.isNotEmpty(id)) {
                    Department department = departmentRepository.findOne(Long.valueOf(id));
                    if (department != null && StringUtils.isNotEmpty(department.getTotalName())) {
                        stringBuffer.append(department.getTotalName() + ",");
                    }
                }
            }
            stationReport.setDeparmentIds(departmentIds);
            stationReport.setSpecifiedType(Constants.MANAGE_DEPARTMENT_EDIT);
            stationReport.setUpdateTime(new Date());
            stationReport.setUpdateTimeStr(new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT).format(new Date()));
            stationReport.setEditUser(user);
            stationReportRepository.save(stationReport);
            ServiceReportRecorder reportRecorder = new ServiceReportRecorder();
            reportRecorder.setType(type);
            UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
            if (userProfile == null) {
                return JsonResponse.errorResponseWithError("抱歉", "未找到当前用户名称");
            }
            reportRecorder.setStationReport(stationReport);
            reportRecorder.setUser(user);
            reportRecorder.setNeedFollowDepartment(stringBuffer.toString());
            Department department = departmentRepository.findOne(departmentId);
            if (department != null) {
                reportRecorder.setDepartment(department);
            }
            note = "备注：" + note;
            reportRecorder.setNote(note);
            serviceReportRecorderRepository.save(reportRecorder);

            QReportRedDot qReportRedDot = QReportRedDot.reportRedDot;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qReportRedDot.deleted.eq(false));
            builder.and(qReportRedDot.enabled.eq(true));
            builder.and(qReportRedDot.departmentId.eq(departmentId));
            builder.and(qReportRedDot.stationReport.id.eq(reportId));
            builder.and(qReportRedDot.type.eq(oldType));
            ReportRedDot redDot = reportRedDotRepository.findOne(builder);
            redDot.setType(type);
            redDot.setUpdateTime(new Date());
            redDot.setUser(user);
            redDot.setIsSendMsg(1);
            redDot.setReaded(true);
            reportRedDotRepository.save(redDot);
            //添加日志
            userLogService.addUserLog(user, stationReport.getStation().getStationNum(), stationReport.getId(), Constants.SERVICE_REPORT, type,
                    LogConstants.business_type_regular_report_edit, null, null);
            return updateMsg(user, telephone.toString(), stationReport, type, department);
        }
        ServiceReportRecorder reportRecorder = new ServiceReportRecorder();
        reportRecorder.setType(type);
        reportRecorder.setNote("备注：" + note);
        reportRecorder.setStationReport(stationReport);
        reportRecorder.setUser(user);
        Department department = departmentRepository.findOne(departmentId);
        if (department != null) {
            reportRecorder.setDepartment(department);
        }

        QReportRedDot qReportRedDot = QReportRedDot.reportRedDot;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qReportRedDot.deleted.eq(false));
        builder.and(qReportRedDot.enabled.eq(true));
        builder.and(qReportRedDot.departmentId.eq(departmentId));
        builder.and(qReportRedDot.stationReport.id.eq(reportId));
        builder.and(qReportRedDot.type.eq(oldType));
        List<ReportRedDot> redDot = (List<ReportRedDot>) reportRedDotRepository.findAll(builder);
        for (ReportRedDot dot : redDot) {
            dot.setType(type);
            dot.setIsSendMsg(1);
            dot.setReaded(true);
            dot.setUser(user);
            reportRedDotRepository.save(dot);
        }
        try {
            //发送短信给部门下的所有人
            stationReportRepository.save(stationReport);
            serviceReportRecorderRepository.save(reportRecorder);
            //添加日志
            userLogService.addUserLog(user, stationReport.getStation().getStationNum(), stationReport.getId(), Constants.SERVICE_REPORT, type,
                    LogConstants.business_type_regular_report, null, null);
            return updateMsg(user, telephone.toString(), stationReport, type, department);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResponse.errorResponseWithError("500", "处理失败");
        }
    }


    private JsonResponse updateMsg(User user, String telephones, StationReport stationReport, String stat, Department department) {
        AdminUserVo adminUserVo = userAdminService.getAdminUser();
        List<User> oppenIdUser = adminUserVo.getUserList();
        UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
        String realName = "";
        if (userProfile != null && StringUtils.isNotEmpty(userProfile.getRealName())) {
            realName = userProfile.getRealName();
        }
        User reportUser = stationReport.getUser();
        userProfile = userProfileRepository.findByUserId(reportUser.getId());
        String reportUserName = "";
        if (userProfile != null && StringUtils.isNotEmpty(userProfile.getRealName())) {
            reportUserName = userProfile.getRealName();
        }
        Station station = stationReport.getStation();
        String stationName = "";
        if (station != null && StringUtils.isNotEmpty(station.getName())) {
            stationName = station.getName();
        }
        String departmentName = "";
        if (StringUtils.isNotEmpty(department.getTotalName())) {
            departmentName = department.getTotalName();
        }
        for (User user1 : oppenIdUser) {
            if (user1.getId().equals(user.getId())) {
                departmentName = "系统管理员";
            }
        }
        String[] typeIds = stationReport.getServiceTypAnswerIds().split(",");
        StringBuffer stringBuffer = new StringBuffer("");
        for (String id : typeIds) {
            if (id.equals("191")) {
                stringBuffer.append("漆星服务");
                break;
            } else {
                if (StringUtils.isNotEmpty(id)) {
                    QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                    if (answerOption != null&& answerOption.getName()!=null) {
                        stringBuffer.append(answerOption.getName() + ",");
                    }
                }
            }
        }
        String[] telephoneArray = telephones.split(",");
        Map<User, Integer> userMap = new HashMap<>();
        for (String str : telephoneArray) {
            if (StringUtils.isNotEmpty(str)) {
                User user1 = userRepository.findByUsername(str);
                if (user1 != null && StringUtils.isNotEmpty(user1.getOpenId())) {
                    userMap.put(user1, 1);
                }
            }
        }
        logger.info("填写报告者为:" + reportUserName);
        logger.info("维修站名称:" + stationName);
        logger.info("服务项目为:" + stringBuffer);
        logger.info("所属部门为：" + departmentName);
        logger.info("操作者为：" + realName);
        logger.info("状态为：" + stat);
        String serviceStr = stringBuffer.toString();
        if (!serviceStr.equals("漆星服务")) {
            serviceStr = serviceStr.substring(0, serviceStr.length() - 1);
        }
        logger.info("去除逗号之后：" + serviceStr);
        try {
//            aliSmsProvider.sendGetReport(telephones, reportUserName, stationName, serviceStr, departmentName, realName, stat);
            logger.info("发送成功");
            logger.info("---------------------------开始推送微信---------------------------");
            String firstData = "您好，" + reportUserName + "在" + stationName + "进行的" + stringBuffer.toString() + "的常规服务报告状态已变更。";
            for (User u : userMap.keySet()) {
                wechatService.pushWechatMessage(u, "K8RDODMnerc2Orj7gbgTYKbalKDRqrJNyX6-s46OUc8", Constants.WECHAT_PUSH_URL, firstData,
                        "可登录漆星服务系统进行查看", realName + "(" + departmentName + ")将状态更新为" + stat, stationReport.getUpdateTimeStr(), "", "", "");
            }
            logger.info("---------------------------推送微信成功---------------------------");
            return JsonResponse.successResponse();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResponse.errorResponseWithError("抱歉", "短信发送失败");
        }
    }

    /**
     * 部门获得已经处理的报告--改
     */
    @Override
    public JsonResponse headGetProcessedReport(User user, Pageable pageable, String province, String city, String brand, String category, String stationName, Long stationId, Long serviceStartTime, Long serviceEndTime,
                                               Long starTime, Long endTime, Integer serviceNum, String serviceType, Boolean type, String score,String stationNum,String department,String payService,
                                               String sentTime,String serviceTime,String userName,String customerStat,String customerType,String paintBrand,String productPosition,String index) {
        UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
        if (userProfile == null) {
            return JsonResponse.errorResponseWithError("抱歉", "当前用户信息不全");
        }
        List<Department> departments = userProfile.getDepartmentList();
        if (departments == null || departments.size() == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "当前用户没有绑定维修站");
        }
        List<Long> idList = new ArrayList<>();
        for (Department d : departments) {
            if (d.getName().equals("经销商") || d.getName().equals("销售部") || d.getName().equals("技术部") || d.getName().equals("市场部") || d.getName().equals("物流部") || d.getName().equals("颜色部")) {
                List<Department> departmentList = departmentRepository.selectParentDeparmentL(d.getId());
                for (Department department1 : departmentList) {
                    idList.add(department1.getId());
                }
            }
            idList.add(d.getId());
        }

        String[] provinces = null;
        String[] cities = null;
        String[] categories = null;
        String[] brands = null;
        String[] serviceTypes = null;
        String[] departmentIds = null;
        Long[] customerStats = null;
        Long[] customerTypes = null;
        String[] paintBrands = null;
        String[] productPositions = null;

        if (!StringUtils.isEmpty(province)) {
            provinces = province.split(",");
        }
        if (!StringUtils.isEmpty(city)) {
            cities = city.split(",");
        }
        if (!StringUtils.isEmpty(category)) {
            categories = category.split(",");
        }
        if (!StringUtils.isEmpty(brand)) {
            brands = brand.split(",");
        }
        if (!StringUtils.isEmpty(serviceType)){
            serviceTypes = serviceType.split(",");
        }
        if (!StringUtils.isEmpty(department)){
            departmentIds = department.split(",");
        }

        if (!StringUtils.isEmpty(paintBrand)){
            paintBrands = paintBrand.split(",");
        }
        if (!StringUtils.isEmpty(productPosition)){
            productPositions = productPosition.split(",");
        }
        if (!StringUtils.isEmpty(customerStat)){
            customerStats = (Long[]) ConvertUtils.convert(customerStat.split(","),Long.class);
        }
        if (!StringUtils.isEmpty(customerType)){
            customerTypes = (Long[]) ConvertUtils.convert(customerType.split(","),Long.class);
        }

        QReportRedDot qReportRedDot = QReportRedDot.reportRedDot;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qReportRedDot.deleted.eq(false));
        builder.and(qReportRedDot.enabled.eq(true));
        builder.and(qReportRedDot.departmentId.in(idList));
        builder.and(qReportRedDot.type.ne(Constants.DEPARTMENT_UNREAD));
        if (stationId != null && stationId != 0) {
            builder.and(qReportRedDot.stationReport.station.id.eq(stationId));
        }

        if (starTime != null && starTime != 0 && endTime != null && endTime != 0) {
            builder.and(qReportRedDot.stationReport.creationTime.after(new Date(starTime)));
            builder.and(qReportRedDot.stationReport.creationTime.before(new Date(endTime)));
        }
        if (serviceStartTime != null && serviceStartTime != 0 && serviceEndTime != null && serviceEndTime != 0) {
            builder.and(qReportRedDot.stationReport.startServiceTime.after(new Date(serviceStartTime)));
            builder.and(qReportRedDot.stationReport.endServiceTime.before(new Date(serviceEndTime)));
        }

        if (customerStats != null) {
            builder.and(qReportRedDot.stationReport.station.customerStat.in(customerStats));
        }
        if (customerTypes != null) {
            builder.and(qReportRedDot.stationReport.station.customerType.in(customerTypes));
        }
        if (stationId != null && stationId != 0) {
            builder.and(qReportRedDot.stationReport.station.id.eq(stationId));
        }
        if (StringUtils.isNotEmpty(province)) {
            builder.and(qReportRedDot.stationReport.station.province.in(provinces));
        }
        if (StringUtils.isNotEmpty(city)) {
            builder.and(qReportRedDot.stationReport.station.city.in(cities));
        }
        if (paintBrands!=null) {
            BooleanBuilder paintBrandBuilder = new BooleanBuilder();
            for (String pBrand:paintBrands){
                paintBrandBuilder.or(qReportRedDot.stationReport.station.paintBrand.like("%" + pBrand + "%"));
            }
            builder.and(paintBrandBuilder);
        }
        if (productPositions!=null) {
            BooleanBuilder ppBuilder = new BooleanBuilder();
            for (String pp:productPositions){
                ppBuilder.or(qReportRedDot.stationReport.station.productPosition.like("%" + pp + "%"));
            }
            builder.and(ppBuilder);
        }
        if (StringUtils.isNotEmpty(brand)) {
            BooleanBuilder builderOr = new BooleanBuilder();
            for (String brandStr: brands){
                builderOr.or(qReportRedDot.stationReport.station.brand.like("%"+brandStr+"%"));
            }
            builder.and(builderOr);
        }
        if (categories != null) {
            builder.and(qReportRedDot.stationReport.station.category.in(categories));
        }
        if (StringUtils.isNotEmpty(stationName)) {
            builder.and(qReportRedDot.stationReport.station.name.like("%" + stationName + "%"));
        }
        if (StringUtils.isNotEmpty(stationNum)) {
            builder.and(qReportRedDot.stationReport.station.stationNum.eq(stationNum));
        }
        if (starTime != null && starTime != 0 && endTime != null && endTime != 0) {
            builder.and(qReportRedDot.stationReport.creationTime.after(new Date(starTime)));
            builder.and(qReportRedDot.stationReport.creationTime.before(new Date(endTime)));
        }
        if (serviceStartTime != null && serviceStartTime != 0 && serviceEndTime != null && serviceEndTime != 0) {
            builder.and(qReportRedDot.stationReport.startServiceTime.after(new Date(serviceStartTime)));
            builder.and(qReportRedDot.stationReport.endServiceTime.before(new Date(serviceEndTime)));
        }
        if (serviceNum != null && serviceNum != 0) {
            builder.and(qReportRedDot.stationReport.user.serviceNum.eq(serviceNum));
        }
        //查询服务项目
        if (serviceTypes != null) {
            //先从报告答案中找出所有填写过ids中任何一个id的答案
            QStationRegularServiceReport qStationRegularServiceReport = QStationRegularServiceReport.stationRegularServiceReport;
            BooleanBuilder regularBuilder = new BooleanBuilder();
            regularBuilder.and(qStationRegularServiceReport.deleted.eq(false));
            regularBuilder.and(qStationRegularServiceReport.enabled.eq(true));
            BooleanBuilder builderOr = new BooleanBuilder();
            for (String id:serviceTypes){
                builderOr.or(qStationRegularServiceReport.answerId.like("%"+id+"%"));
            }
            regularBuilder.and(builderOr);
            List<StationRegularServiceReport> list = (List<StationRegularServiceReport>) stationRegularServiceReportRepository.findAll(builderOr);
            if (list == null || list.size()==0){
                return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
            }
            //获取答案针对的报告站点报告id合集
            Long[] reportIDs = new Long[list.size()];
            for (int i=0;i<list.size();i++){
                reportIDs[i] = list.get(i).getStationReport().getId();
            }
            builder.and(qReportRedDot.stationReport.id.in(reportIDs));
        }
        if (StringUtils.isNotEmpty(userName) || departments != null) {
            QStationColorReport qStationColorReport = QStationColorReport.stationColorReport;
            QUserProfile qUserProfile = QUserProfile.userProfile;
            BooleanBuilder booleanBuilder = new BooleanBuilder();
            booleanBuilder.and(qUserProfile.deleted.eq(false));
            booleanBuilder.and(qUserProfile.enabled.eq(true));
            booleanBuilder.and(qUserProfile.user.userFlag.in(0,2));
            boolean flag = false;
            if (StringUtils.isNotEmpty(userName)) {
                flag = true;
                booleanBuilder.and(qUserProfile.realName.like("%" + userName + "%"));
            }
            if (departmentIds != null){
                flag = true;
                booleanBuilder.and(qUserProfile.user.userFlag.in(0,2));
                booleanBuilder.and(qUserProfile.user.userType.in(UserType.admin,UserType.dealers,UserType.insiders));
                for (String str:departmentIds){
                    booleanBuilder.or(qUserProfile.departmentList.any().name.eq(str));
                }
            }
            if (flag) {
                List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(booleanBuilder);
                if (userProfileList == null || userProfileList.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> userIds = new ArrayList<>();
                for (UserProfile user1 : userProfileList) {
                    userIds.add(user1.getUser().getId());
                }
                BooleanBuilder colorBuilder = new BooleanBuilder();
                colorBuilder.and(qStationColorReport.deleted.eq(false));
                colorBuilder.and(qStationColorReport.enabled.eq(true));
                colorBuilder.and(qStationColorReport.stationReport.station.report_finished.in(1, 2, 3));
                colorBuilder.and(qStationColorReport.stationReport.user.id.in(userIds));
                List<StationColorReport> list = (List<StationColorReport>) stationColorReportRepository.findAll(colorBuilder);
                if (list == null || list.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> ids = new ArrayList<>();
                for (StationColorReport report : list) {
                    if (report.getReportId() != null) {
                        ids.add(Long.parseLong(report.getReportId()));
                    }
                }
                builder.and(qReportRedDot.stationReport.id.in(ids));
            }
        }
        if (payService != null || sentTime!=null || serviceTime!=null){
            QStationColorReport qStationColorReport = QStationColorReport.stationColorReport;
            BooleanBuilder builderStationColor = new BooleanBuilder();
            builderStationColor.and(qStationColorReport.deleted.eq(false));
            builderStationColor.and(qStationColorReport.enabled.eq(true));
            boolean flag = false;
            if (payService!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+payService+"%"));
            }
            if (sentTime!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+sentTime+"%"));
            }
            if (serviceTime!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+serviceTime+"%"));
            }
            if (flag) {
                List<StationColorReport> stationColorReports = (List<StationColorReport>) stationColorReportRepository.findAll(builderStationColor);
                if (stationColorReports == null || stationColorReports.size() == 0) {
                    return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
                }
                List<Long> Ids = new ArrayList<>();
                for (StationColorReport report : stationColorReports) {
                    Ids.add(report.getStationReport().getStation().getId());
                }
                builder.and(qReportRedDot.stationReport.station.id.in(Ids));
            }
        }
        if (StringUtils.isNotEmpty(score)) {
            QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
            BooleanBuilder builderCustomer = new BooleanBuilder();
            builderCustomer.and(qCustomerRegularReport.deleted.eq(false));
            builderCustomer.and(qCustomerRegularReport.enabled.eq(true));
            String[] str = new String[61];
            for (int i = 0; i < str.length; i++) {
                str[i] = i + "";
            }
            String[] notStr = new String[39];
            int _index = 61;
            for (int i = 0; i < 39; i++) {
                notStr[i] = _index + "";
                _index += 1;
            }
            if (score.equals(Constants.FULL_MARKS)) {
                builderCustomer.and(qCustomerRegularReport.score.eq("100"));
            }
            if (score.equals(Constants.MORE_THAN_SIXTY)) {
                builderCustomer.and(qCustomerRegularReport.score.in(notStr));
            }
            if (score.equals(Constants.BELOW_THAN_SIXTY)) {
                builderCustomer.and(qCustomerRegularReport.score.in(str));
            }
            List<CustomerRegularReport> list = (List<CustomerRegularReport>) customerRegularReportRepository.findAll(builderCustomer);
            if (list == null || list.size()==0){
                return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
            }
            Long[] reportIDs = new Long[list.size()];
            for (int i=0;i<list.size();i++){
                reportIDs[i] = list.get(i).getCustomerReport().getId();
            }
            builder.and(qReportRedDot.stationReport.id.in(reportIDs));

        }
        if (StringUtils.isNotEmpty(index)) {
            builder.and(qReportRedDot.type.eq(index));
        }
        Sort sort = new Sort(Sort.Direction.DESC, "creationTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<ReportRedDot> redDots = reportRedDotRepository.findAll(builder, pageable);
        List<TechColorAuditingReports> responseList = toReportResponse(redDots.getContent());
        Page<TechColorAuditingReports> page = new PageImpl(responseList, pageable, redDots.getTotalElements());
        return JsonResponse.successResponseWithPageData(page);
    }

    /**
     * 封装负责人被指定的报告--改
     */
    private List<TechColorAuditingReports> toReportResponse(List<ReportRedDot> redDots) {
        List<TechColorAuditingReports> reportsList = new ArrayList<>();
        for (ReportRedDot dot : redDots) {
            TechColorAuditingReports reports = new TechColorAuditingReports();
            StationReport stationReport = dot.getStationReport();
            if (stationReport != null) {
                User user = stationReport.getEditUser();
                if (user != null) {
                    UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
                    if (userProfile != null) {
                        reports.setEditUserName(userProfile.getRealName());
                    }
                }
            }
            Department department = departmentRepository.findOne(dot.getDepartmentId());
            if (department != null) {
                reports.setDepartmentTotalName(department.getTotalName());
                reports.setDepartmentId(department.getId());
            } else {
                reports.setDepartmentTotalName("");
                reports.setDepartmentId(0L);
            }
            if (dot.getType().equals(Constants.SPECIFEDTYPE)) {
                reports.setReaded(false);
            } else {
                reports.setReaded(true);
            }
            if (StringUtils.isNotEmpty(dot.getType())) {
                reports.setType(dot.getType());
            } else {
                reports.setType("");
            }
            reports.setRecorderType(dot.getType());
            reports.setDateTime(dot.getStationReport().getUpdateTimeStr());
            reports.setId(dot.getStationReport().getId());
            reports.setStationName(dot.getStationReport().getStation().getProvince() + dot.getStationReport().getStation().getCity() + dot.getStationReport().getStation().getName());
            UserProfile userProfile = userProfileRepository.findByUserId(dot.getStationReport().getUser().getId());
            if (userProfile == null) {
                reports.setUserName("");
            } else {
                reports.setUserName(userProfile.getRealName());
            }
            StationRegularServiceReport regularServiceReport = stationRegularServiceReportRepository.selectQuestion(dot.getStationReport().getId(), 155L);
            String[] targetIds = regularServiceReport.getAnswerId().split(",");
            StringBuffer stringBuffer = new StringBuffer("");
            for (String id : targetIds) {
                QuestionAnswerOption questionAnswerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                if (questionAnswerOption != null&& questionAnswerOption.getName()!=null) {
                    String targer = questionAnswerOption.getName();
                    if (StringUtils.isNotEmpty(targer)) {
                        stringBuffer.append(targer + ",");
                    }
                }
            }
            reports.setTarget(stringBuffer.toString());
            reportsList.add(reports);
        }
        return reportsList;
    }


    /**
     * 封装返回类
     *
     * @param stationReports
     * @return
     */
    private List<TechColorAuditingReports> toResponseVO(List<StationReport> stationReports) {
        List<TechColorAuditingReports> reportsList = new ArrayList<>();
        for (StationReport report : stationReports) {
            TechColorAuditingReports techColorAuditingReports = new TechColorAuditingReports();
            techColorAuditingReports.setId(report.getId());
            String provinceStr = "";
            String cityStr = "";
            if (StringUtils.isNotEmpty(report.getStation().getProvince())) {
                provinceStr = report.getStation().getProvince();
            }
            if (StringUtils.isNotEmpty(report.getStation().getCity())) {
                cityStr = report.getStation().getCity();
            }
            if (provinceStr.equals(cityStr)) {
                techColorAuditingReports.setStationName(provinceStr + report.getStation().getName());
            } else {
                techColorAuditingReports.setStationName(provinceStr + cityStr + report.getStation().getName());
            }
            techColorAuditingReports.setDateTime(report.getCreationTimeStr());
            techColorAuditingReports.setReaded(report.isAdminReaded());
            techColorAuditingReports.setFollowed(report.isIsfollowed());
            if (StringUtils.isNotEmpty(report.getDeparmentIds())) {
                techColorAuditingReports.setUserIds(report.getDeparmentIds());
            } else {
                techColorAuditingReports.setUserIds("");
            }
            if (StringUtils.isNotEmpty(report.getExceptionType())) {
                techColorAuditingReports.setType(report.getExceptionType());
            } else {
                techColorAuditingReports.setType("");
            }
            UserProfile userProfile = userProfileRepository.findByUserId(report.getUser().getId());
            if (userProfile == null) {
                techColorAuditingReports.setUserName("默认的名字");
            } else {
                techColorAuditingReports.setUserName(userProfile.getRealName());
            }
            StationRegularServiceReport regularServiceReport = stationRegularServiceReportRepository.selectQuestion(report.getId(), 155L);
            if (regularServiceReport == null) {
                techColorAuditingReports.setTarget("");
            } else {
                String[] targetIds = regularServiceReport.getAnswerId().split(",");
                StringBuffer stringBuffer = new StringBuffer("");
                for (String id : targetIds) {
                    QuestionAnswerOption questionAnswerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                    if (questionAnswerOption != null&& questionAnswerOption.getName()!=null){
                        String targer = questionAnswerOption.getName();
                        if (StringUtils.isNotEmpty(targer)) {
                            stringBuffer.append(targer + ",");
                        }
                    }
                }
                techColorAuditingReports.setTarget(stringBuffer.toString());
            }
            reportsList.add(techColorAuditingReports);
        }
        return reportsList;
    }


    @Autowired
    private StationReportUnFinshedRepository stationReportUnFinshedRepository;

    @Override
    public JsonResponse getTempReport(Long reportId) {
        QStationRegularServiceReportUnFinshed qStationRegularServiceReportUnFinshed = QStationRegularServiceReportUnFinshed.stationRegularServiceReportUnFinshed;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationRegularServiceReportUnFinshed.deleted.eq(false));
        builder.and(qStationRegularServiceReportUnFinshed.enabled.eq(true));
        builder.and(qStationRegularServiceReportUnFinshed.stationReportTemp.id.eq(reportId));
        List<StationRegularServiceReportUnFinshed> reportUnFinsheds = (List<StationRegularServiceReportUnFinshed>) stationRegularServiceReportUnFinshedRepository.findAll(builder);
        StationRegularReport stationRegularReport = new StationRegularReport();
        stationRegularReport.setStationRegularServiceReportUnFinsheds(reportUnFinsheds);
        stationRegularReport.setStationReportTemp(stationReportUnFinshedRepository.findOne(reportId));
        return JsonResponse.successResponseWithData(stationRegularReport);
    }


}
